<template>
  <div class='container'>
    <el-card class="box-card" style="margin:20px">
      <div slot="header" class="clearfix">
        <span>试题录入</span>
      </div>
      <el-form ref="addQuestion" :model="form" :rules="rules" label-width="80px" style="margin-left:30px">

        <el-form-item label="学科:" prop="subjectID">
          <el-select v-model="form.subjectID" placeholder="请选择">
            <el-option v-for="item in subject" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录:" prop="catalogID">
          <el-select v-model="form.catalogID" placeholder="请选择">
            <el-option v-for="item in directoryList" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="企业:" prop="enterpriseID">
          <el-select v-model="form.enterpriseID" placeholder="请选择">
            <el-option v-for="item in company" :key="item.id" :label="item.company" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="城市:" class="cityStyle" prop="province">
          <el-select v-model="city1" placeholder="请选择">
            <el-option v-for="item,index in city_1" :key="index" :label="item" :value="item"></el-option>
          </el-select>
          <el-select v-model="city2" placeholder="请选择">
            <el-option v-for="item,index in city_2" :key="index" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="方向:" prop="direction">
          <el-select v-model="form.direction" placeholder="请选择">
            <el-option v-for="item,index in direction" :key="index" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="题型:" prop="questionType">
          <el-radio-group v-model="type">
            <el-radio label="单选"></el-radio>
            <el-radio label="多选"></el-radio>
            <el-radio label="简答"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="难度:" prop="difficulty">
          <el-radio-group v-model="form.difficulty">
            <el-radio label="简单"></el-radio>
            <el-radio label="一般"></el-radio>
            <el-radio label="困难"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="题干:" prop="question">
          <quill-editor v-model="form.question" :options="editorOptions" style="height:200px"></quill-editor>
        </el-form-item>
        <br>
        <el-form-item label="选项:" style="margin-top:40px" v-if="showType">
          <!-- 单选 -->
          <el-radio-group v-model="option" v-if="type==='单选'">
            <div v-for="item in form.options" :key="item.code" style="margin-bottom:20px;display:flex;">
              <el-radio :label="item.code" style="margin-top:10px">
                {{item.code}}: <el-input v-model="item.title"></el-input>
              </el-radio>
              <el-upload class="avatar-uploader" action="https://jsonplaceholder.typicode.com/posts/" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                <img v-if="item.img" :src="item.img" class="avatar">
                <i v-else class="el-icon-circle-close avatar-uploader-icon"></i>
              </el-upload>
            </div>
          </el-radio-group>
          <!-- 多选 -->
          <el-checkbox-group v-model="option" v-else-if="type==='多选'">
            <div v-for="item in form.options" :key="item.code" style="margin-bottom:20px;display:flex;">
              <el-checkbox :label="item.code" style="margin-top:10px">
                {{item.code}}: <el-input v-model="item.title"></el-input>
              </el-checkbox>
              <el-upload class="avatar-uploader" action="https://jsonplaceholder.typicode.com/posts/" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                <img v-if="item.img" :src="item.img" class="avatar">
                <i v-else class="el-icon-circle-close avatar-uploader-icon"></i>
              </el-upload>
            </div>
          </el-checkbox-group>
        </el-form-item>
        <el-button type="danger" v-if="showType" size="mini" style="padding:10px 15px;margin-left:80px;margin-bottom:20px" @click="addChoose">+增加选项与答案</el-button>
        <br>
        <el-form-item label="解析视频:" style="margin-top:20px">
          <el-input v-model="form.videoURL"></el-input>
        </el-form-item>
        <el-form-item label="答案解析:" class="awserStyle" prop="answer">
          <quill-editor v-model="form.answer" :options="editorOptions" style="height:200px;margin-bottom:40px"></quill-editor>
        </el-form-item>
        <br>
        <el-form-item label="题目备注:">
          <el-input type="textarea" v-model="form.remarks"></el-input>
        </el-form-item>
        <el-form-item label="试题标签:" class="tagStyle" prop="tags">
          <el-select v-model="form.tags" placeholder="请选择">
            <el-option v-for="item in tagList" :key="item.value" :label="item.label" :value="item.label"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click.stop.prevent="onSubmit">确认提交</el-button>

        </el-form-item>

      </el-form>
    </el-card>
  </div>
</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
import { simple as subjectsSimple } from '@/api/hmmm/subjects.js'
import { provinces, citys } from '@/api/hmmm/citys.js'
import { simple as tagsSimple } from '@/api/hmmm/tags.js'
import { simple as directorySimple } from '@/api/hmmm/directorys.js'
import { list as companyList } from '@/api/hmmm/companys.js'
// import { simple as articlesSimple } from '@/api/hmmm/articles.js'
import { difficulty, questionType, direction as directionList } from '@/api/hmmm/constants.js'
import { add } from '@/api/hmmm/questions.js'

export default {
  data () {
    return {
      // 学科
      subject: [],
      // 目录列表
      directoryList: [],
      // 企业
      company: [],
      // 城市
      city_1: [],
      city_2: [],
      city1: '',
      city2: '',
      // 方向
      direction: [],
      // 题型
      type: '单选',
      showType: true,
      // 标签
      tagList: [],
      list: [],
      // 选项
      option: '',
      editorOptions: {
        placeholder: '',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            [{ list: 'ordered' }, { list: 'bullet' }],
            ['blockquote'],
            ['code-block', 'image', 'link']
          ],
          // 语法高亮
          syntax: {
            highlight: text => hljs.highlightAuto(text).value
          }
        }
      },

      form: {
        // 学科
        subjectID: '',
        // 目录列表
        catalogID: '',
        // 企业
        enterpriseID: '',
        // 城市
        province: '',
        // 地区
        city: '',
        // 方向
        direction: '',
        // 题型
        questionType: '单选',
        // 难度
        difficulty: '简单',
        // 题干
        question: null,
        // 选项
        options: [
          {
            code: 'A',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'B',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'C',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'D',
            title: '',
            img: '',
            isRight: false
          }

        ],
        // 视频链接
        videoURL: '',
        // 答案解析
        answer: null,
        // 题目备注
        remarks: '',
        // 标题标签
        tags: ''

      },
      // 非空校验
      rules: {
        subjectID: [
          { required: true, message: '学科不能为空', trigger: ['blur', 'change'] }
        ],
        catalogID: [
          { required: true, message: '目录不能为空', trigger: ['blur', 'change'] }
          // { min: 1, max: 4, message: '用户姓名为1-4位', trigger: ['blur', 'change'] }
        ],
        enterpriseID: [
          { required: true, message: '企业不能为空', trigger: ['blur', 'change'] }
        ],
        province: [
          { required: true, message: '城市不能为空', trigger: ['blur', 'change'] }
        ],
        direction: [
          { required: true, message: '方向不能为空', trigger: ['blur', 'change'] }
        ],
        questionType: [
          { required: true, message: '题型不能为空', trigger: ['blur', 'change'] }
        ],
        difficulty: [
          { required: true, message: '难度不能为空', trigger: ['blur', 'change'] }
        ],
        question: [
          { required: true, message: '题干不能为空', trigger: ['blur', 'change'] }
        ],
        answer: [
          { required: true, message: '答案解析不能为空', trigger: ['blur', 'change'] }
        ],
        tags: [
          { required: true, message: '标签不能为空', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  components: { quillEditor },
  created () {
    this.getSubjectList()
    this.getCityList()
    this.getTagList()
    this.getdirectoryList()
    this.getcompanyList()
    this.getarticleList()
  },
  methods: {
    // 提交表单
    onSubmit () {
      this.$refs.addQuestion.validate(async valid => {
        if (!valid) return
        const ret = await this.$confirm('确认填加试题吗?', '温馨提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        // 取消添加
        if (ret === 'cancel') return
        this.difChange()
        this.queChange()
        this.sameIsRight()
        try {
          const ret1 = await add(this.form)
          if (ret1.status === 200) {
            this.$message.success('填加试题成功')
            this.$refs.addQuestion.resetFields()
            this.$router.replace('/questions/list')
          }
        } catch (err) {
          this.$message.error('填加试题失败')
        }
      })
    },
    // 完善表单题型,难度
    // 上传图片
    handleAvatarSuccess (res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 得到学科列表
    async getSubjectList () {
      const ret = await subjectsSimple()
      this.subject = ret.data
    },
    // 得到城市列表
    getCityList () {
      const ret = provinces()
      this.city_1 = ret
    },
    // 得到城市下的县的列表
    getCityLastList () {
      if (!this.city1) return
      this.city_2 = citys(this.city1)
    },
    // 得到目录列表
    async getdirectoryList () {
      const ret = await directorySimple()
      this.directoryList = ret.data
    },
    // 得到企业列表
    async getcompanyList () {
      const ret = await companyList()
      this.company = ret.data.items
    },
    // 得到方向列表
    getarticleList () {
      this.direction = directionList
    },
    // 得到标签列表
    async getTagList () {
      const ret = await tagsSimple()
      this.tagList = ret.data
    },
    // 增加选项按钮
    addChoose () {
      const i = this.form.options.length
      const ary = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
      if (i === 26) {
        this.$message('选项达到上限')
        return
      }
      this.form.options.push({
        code: ary[i],
        title: '',
        img: '',
        isRight: false
      })
    },
    //  转换表单难度和题型文字内容为value值
    // 难度转换
    difChange () {
      const ret = difficulty.find((item) => {
        return item.label === this.form.difficulty
      })
      this.form.difficulty = `${ret.value}`
    },
    // 题型转换
    queChange () {
      const ret = questionType.find((item) => {
        return item.label === this.form.questionType
      })
      this.form.questionType = `${ret.value}`
    },
    // 将form里的isRight跟option统一
    sameIsRight () {
      // 单选和多选
      if (this.form.questionType === '1') {
        const Ary = this.form.options
        Ary.forEach((item) => {
          if (item.code === this.option) {
            item.isRight = true
          }
        })
      } else if (this.form.questionType === '2') {
        const Ary = this.form.options
        Ary.forEach(item => {
          const ret = this.option.includes(item.code)
          if (ret) {
            item.isRight = true
          }
        })
      } else {
        this.form.options = []
      }
    }
  },
  watch: {
    city1: {
      handler (newVal, oldVal) {
        this.getCityLastList()
        this.city2 = ''
      },
      deep: true,
      immediate: false
    },

    city2: {
      handler (newVal, oldVal) {
        // 同步表单城市
        this.form.province = `${this.city1}`
        this.form.city = `${this.city2}`
      },
      deep: true,
      immediate: false
    },
    type: {
      handler (val) {
        if (this.type === '简答') {
          this.showType = false
        } else {
          if (this.type === '单选') {
            this.option = ''
          } else {
            this.option = []
          }
          this.showType = true
        }
        // 同步表单题型
        this.form.questionType = `${this.type}`
      },
      deep: true,
      immediate: false
    }
  }
}

</script>

<style lang='scss'>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 60px;
  line-height: 60px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 60px;
  display: block;
}
.el-textarea__inner {
  width: 400px;
  height: 96px;
}
.el-input__inner {
  width: 400px;
}
.el-card__body {
  // 动态绑定样式
  .el-radio-group .el-input__inner {
    width: 240px;
  }
  .el-checkbox-group .el-input__inner {
    width: 240px;
    margin-right: 15px;
  }
}

.el-radio-group {
  width: 400px;
  label {
    margin-right: 10px !important;
  }
}
.cityStyle .el-input__inner {
  width: 198px;
  margin-right: 2px;
}

.avatar-uploader .el-upload {
  width: 100px;
  height: 60px;
  overflow: inherit;

  .avatar-uploader-icon {
    width: 100px;
    height: 60px;
    position: relative;

    line-height: 0;
    &::before {
      content: '上传图片';
      position: absolute;
      width: 100%;
      top: 30px;
      left: 0px;
      font-size: 14px;
      color: #000;
    }
    &::after {
      // overflow: none;
      position: absolute;
      right: -10px;
      content: '\e78d';
      font-size: 18px;
    }

    // .el-icon-circle-close::before {

    //   position: absolute;
    //   top: 0px;
    // }
  }
}
.el-form {
  .awserStyle {
    .el-form-item__label {
      width: 83px !important;
    }
  }
  .tagStyle {
    .el-form-item__label {
      width: 83px !important;
    }
  }
}
// // 答案解析样式调整
// .el-form-item--medium {

// }
</style>
